{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sentiment Classification with FHE\n",
    "\n",
    "This notebook tackles sentiment classification with Fully Homomorphic Encryption. Let's imagine some client (could be a user or a company) wants to predict whether a specific text (e.g., a tweet) contains positive, neutral or negative feedback using a cloud service provider without actually revealing the text during the process.\n",
    "\n",
    "To do this, we use a machine learning model that can predict over encrypted data thanks to the Concrete ML library available on [GitHub](https://github.com/zama-ai/concrete-ml).\n",
    "\n",
    "The data-set we use in this notebook can be found on [Kaggle](https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment). \n",
    " \n",
    "We present two different ways to encode the text:\n",
    "1. A basic **TF-IDF** approach, which essentially looks at how often a word appears in the text.\n",
    "2. An advanced **transformer** embedding of the text using the Huggingface repository.\n",
    "\n",
    "The main assumption of this notebook is that clients, who want to have their text analyzed in a privacy preserving manner, can encode the text using a predefined representation before encrypting the data. The FHE-friendly model is thus trained in the clear beforehand for the given task, here classification, over theses representations using a relevant training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No CUDA runtime is found, using CUDA_HOME='/usr/local/cuda'\n"
     ]
    }
   ],
   "source": [
    "# Import the required packages\n",
    "import time\n",
    "\n",
    "import numpy\n",
    "import pandas as pd\n",
    "import requests\n",
    "from sklearn.metrics import average_precision_score\n",
    "from sklearn.model_selection import GridSearchCV, train_test_split\n",
    "\n",
    "from concrete.ml.sklearn import XGBClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = (\n",
    "    \"https://huggingface.co/datasets/osanseviero/twitter-airline-sentiment/resolve/main/Tweets.csv\"\n",
    ")\n",
    "response = requests.get(url)\n",
    "\n",
    "with open(\"Tweets.csv\", \"wb\") as file:\n",
    "    file.write(response.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Proportion of positive examples: 16.14%\n",
      "Proportion of negative examples: 62.69%\n",
      "Proportion of neutral examples: 21.17%\n"
     ]
    }
   ],
   "source": [
    "train = pd.read_csv(\"Tweets.csv\", index_col=0)\n",
    "text_X = train[\"text\"]\n",
    "y = train[\"airline_sentiment\"]\n",
    "y = y.replace([\"negative\", \"neutral\", \"positive\"], [0, 1, 2])\n",
    "\n",
    "pos_ratio = y.value_counts()[2] / y.value_counts().sum()\n",
    "neg_ratio = y.value_counts()[0] / y.value_counts().sum()\n",
    "neutral_ratio = y.value_counts()[1] / y.value_counts().sum()\n",
    "print(f\"Proportion of positive examples: {round(pos_ratio * 100, 2)}%\")\n",
    "print(f\"Proportion of negative examples: {round(neg_ratio * 100, 2)}%\")\n",
    "print(f\"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split in train test\n",
    "text_X_train, text_X_test, y_train, y_test = train_test_split(\n",
    "    text_X, y, test_size=0.1, random_state=42\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. Text representation using TF-IDF\n",
    "\n",
    "[Term Frequency-Inverse Document Frequency](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) (TF-IDF) also known as  is a numerical statistic that is used to compute the importance of a term in a document. The higher the TF-IDF score, the more important the term is to the document.\n",
    "\n",
    "We compute it as follows:\n",
    "\n",
    "$$ \\mathsf{TF\\textrm{-}IDF}(t,d,D) = \\mathsf{TF}(t,d) * \\mathsf{IDF}(t,D) $$\n",
    "\n",
    "where: $\\mathsf{TF}(t,d)$ is the term frequency of term $t$ in document $d$, $\\mathsf{IDF}(t,D)$ is the inverse document frequency of term $t$ in document collection $D$.\n",
    "\n",
    "Here we use the scikit-learn implementation of TF-IDF vectorizer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's first build a representation vector from the text\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "\n",
    "tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words=\"english\")\n",
    "X_train = tfidf_vectorizer.fit_transform(text_X_train)\n",
    "X_test = tfidf_vectorizer.transform(text_X_test)\n",
    "\n",
    "# Make our train and test dense array\n",
    "X_train = X_train.toarray()\n",
    "X_test = X_test.toarray()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's build our model\n",
    "model = XGBClassifier()\n",
    "\n",
    "# A gridsearch to find the best parameters\n",
    "parameters = {\n",
    "    \"n_bits\": [2, 3],\n",
    "    \"max_depth\": [1],\n",
    "    \"n_estimators\": [10, 30, 50],\n",
    "    \"n_jobs\": [-1],\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={&#x27;max_depth&#x27;: [1], &#x27;n_bits&#x27;: [2, 3],\n",
       "                         &#x27;n_estimators&#x27;: [10, 30, 50], &#x27;n_jobs&#x27;: [-1]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={&#x27;max_depth&#x27;: [1], &#x27;n_bits&#x27;: [2, 3],\n",
       "                         &#x27;n_estimators&#x27;: [10, 30, 50], &#x27;n_jobs&#x27;: [-1]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</pre></div></div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
       "                         'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
       "             scoring='accuracy')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Run the gridsearch\n",
    "grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best score: 0.6842744383727991\n",
      "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
     ]
    }
   ],
   "source": [
    "# Check the accuracy of the best model\n",
    "print(f\"Best score: {grid_search.best_score_}\")\n",
    "\n",
    "# Check best hyper-parameters\n",
    "print(f\"Best parameters: {grid_search.best_params_}\")\n",
    "\n",
    "# Extract best model\n",
    "best_model = grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.6810\n",
      "Average precision score for positive class: 0.5615\n",
      "Average precision score for negative class: 0.8349\n",
      "Average precision score for neutral class: 0.3820\n"
     ]
    }
   ],
   "source": [
    "# Compute the average precision for each class\n",
    "y_proba_test_tfidf = best_model.predict_proba(X_test)\n",
    "\n",
    "# Compute accuracy\n",
    "y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)\n",
    "accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)\n",
    "print(f\"Accuracy: {accuracy_tfidf:.4f}\")\n",
    "\n",
    "y_pred_positive = y_proba_test_tfidf[:, 2]\n",
    "y_pred_negative = y_proba_test_tfidf[:, 0]\n",
    "y_pred_neutral = y_proba_test_tfidf[:, 1]\n",
    "\n",
    "ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)\n",
    "ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)\n",
    "ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)\n",
    "\n",
    "print(f\"Average precision score for positive class: \" f\"{ap_positive_tfidf:.4f}\")\n",
    "print(f\"Average precision score for negative class: \" f\"{ap_negative_tfidf:.4f}\")\n",
    "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_tfidf:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 most positive tweets (class 2):\n",
      "@united sent a DM just now. Thanks I am incredibly happy the fast response I got via Twitter than via customer care. Thank you\n",
      "@JetBlue Great Thank you, lets hope so! Could you please notify me if flight 2302 leaves JFK? Thank you again\n",
      "@AmericanAir Great, thanks. Followed.\n",
      "@SouthwestAir I continue to be amazed by the amazing customer service.  Thank you SWA!\n",
      "@JetBlue Awesome thanks! Thanks for the quick response. You guys ROCK! :)\n",
      "----------------------------------------------------------------------------------------------------\n",
      "5 most negative tweets (class 0):\n",
      "@USAirways been on hold 2 hours for a Cancelled Flighted flight. I understand the delay. I don't understand you auto-reFlight Booking Problems me on TUESDAY. HELP!\n",
      "@SouthwestAir 2 hours on hold for customer service never us SW again\n",
      "@SouthwestAir  placed on hold for total of two hours today after flight was Cancelled Flightled. Online option not available. What to do?\n",
      "@southwestair I've been on hold for 2 hours to reschedule my Cancelled Flightled flight for the morning. What gives? I need help NOW\n",
      "@USAirways Customer service is dead. Last wk, flts delayed/Cancelled Flighted. Bags lost 4 days. Last nt, flt delayed/Cancelled Flighted.  No meal voucher?\n"
     ]
    }
   ],
   "source": [
    "# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
    "print(\"5 most positive tweets (class 2):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test.iloc[y_proba_test_tfidf[:, 2].argsort()[-1 - i]])\n",
    "\n",
    "print(\"-\" * 100)\n",
    "\n",
    "print(\"5 most negative tweets (class 0):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test.iloc[y_proba_test_tfidf[:, 0].argsort()[-1 - i]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Compilation time: 8.4803 seconds\n",
      "FHE inference time: 1.1835 seconds\n"
     ]
    }
   ],
   "source": [
    "# Compile the model to get the FHE inference engine\n",
    "# (this may take a few minutes depending on the selected model)\n",
    "start = time.perf_counter()\n",
    "best_model.compile(X_train)\n",
    "end = time.perf_counter()\n",
    "print(f\"Compilation time: {end - start:.4f} seconds\")\n",
    "\n",
    "# Let's write a custom example and predict in FHE\n",
    "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
    "X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()\n",
    "clear_proba = best_model.predict_proba(X_tested_tweet)\n",
    "\n",
    "# Now let's predict with FHE over a single tweet and print the time it takes\n",
    "start = time.perf_counter()\n",
    "decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe=\"execute\")\n",
    "end = time.perf_counter()\n",
    "print(f\"FHE inference time: {end - start:.4f} seconds\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Probabilities from the FHE inference: [[0.50224707 0.25647676 0.24127617]]\n",
      "Probabilities from the clear model: [[0.50224707 0.25647676 0.24127617]]\n"
     ]
    }
   ],
   "source": [
    "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
    "print(f\"Probabilities from the clear model: {clear_proba}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To sum up, \n",
    "- We trained a XGBoost model over TF-IDF representation of the tweets and their respective sentiment class. \n",
    "- The grid search gives us a model that achieves around ~70% accuracy.\n",
    "- Given the imbalance in the classes, we rather compute the average precision per class.\n",
    "\n",
    "Now we will see how we can approach the problem by leveraging the transformers power."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. A transformer approach to text representation\n",
    "\n",
    "[**Transformers**](https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)) are neural networks that are often trained to predict the next words to appear in a text (this is commonly called self-supervised learning). \n",
    "\n",
    "They are powerful tools for all kind of Natural Language Processing tasks but supporting a transformer model in FHE might not always be ideal as they are quite big models. However, we can still leverage their hidden representation for any text and feed it to a more FHE friendly machine learning model (in this notebook we will use XGBoost) for classification.\n",
    "\n",
    "Here we will use the transformer model from the amazing [**Huggingface**](https://huggingface.co/) repository."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "aacce1e5a7d747028d7898f3c190c0cb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)lve/main/config.json:   0%|          | 0.00/929 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8f046a245efd4588b33b1f93724800c9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)olve/main/vocab.json:   0%|          | 0.00/899k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "66adaf9f468743b4995b72c67b1567d6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)olve/main/merges.txt:   0%|          | 0.00/456k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d8e102d5ef7d416f9ae2b4b1c2a32a5b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)cial_tokens_map.json:   0%|          | 0.00/239 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9908c89d2426455c827d4d363dce17fd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading pytorch_model.bin:   0%|          | 0.00/501M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.weight', 'roberta.pooler.dense.bias']\n",
      "- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g., initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import tqdm\n",
    "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
    "\n",
    "# Add MPS (for macOS with Apple Silicon or AMD GPUs) support when error is fixed. For now, we\n",
    "# observe a decrease in torch's top1 accuracy when using MPS devices\n",
    "# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/3953\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "\n",
    "# Load the tokenizer (converts text to tokens)\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n",
    "\n",
    "# Load the pre-trained model\n",
    "transformer_model = AutoModelForSequenceClassification.from_pretrained(\n",
    "    \"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 30/30 [00:06<00:00,  4.78it/s]\n"
     ]
    }
   ],
   "source": [
    "# Let's first see what are the model performance by itself\n",
    "list_text_X_test = text_X_test.tolist()\n",
    "\n",
    "tokenized_text_X_test = tokenizer.batch_encode_plus(\n",
    "    list_text_X_test, pad_to_max_length=True, return_tensors=\"pt\"\n",
    ")[\"input_ids\"]\n",
    "\n",
    "# Depending on the hardware used, the number of examples to be processed can be reduced\n",
    "# Here we split the data into 100 examples per batch\n",
    "tokenized_text_X_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)\n",
    "transformer_model = transformer_model.to(device)\n",
    "\n",
    "outputs = []\n",
    "for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):\n",
    "    tokenized_x = tokenized_x_test.to(device)\n",
    "    output_batch = transformer_model(tokenized_x)[\"logits\"]\n",
    "    output_batch = output_batch.detach().cpu().numpy()\n",
    "    outputs.append(output_batch)\n",
    "\n",
    "outputs = numpy.concatenate(outputs, axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Predictions for the first 3 tweets:\n",
      " [[-2.3807464  -0.6180208   2.990075  ]\n",
      " [ 2.0166507   0.49380797 -2.8006463 ]\n",
      " [ 2.3892698   0.13443631 -2.687382  ]]\n"
     ]
    }
   ],
   "source": [
    "# Let's see what the transformer model predicts\n",
    "print(f\"Predictions for the first 3 tweets:\\n {outputs[:3]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8053\n",
      "Average precision score for positive class: 0.8548\n",
      "Average precision score for negative class: 0.9548\n",
      "Average precision score for neutral class: 0.6801\n"
     ]
    }
   ],
   "source": [
    "# Compute the metrics for each class\n",
    "\n",
    "# Compute accuracy\n",
    "accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)\n",
    "print(f\"Accuracy: {accuracy_transformer_only:.4f}\")\n",
    "\n",
    "y_pred_positive = outputs[:, 2]\n",
    "y_pred_negative = outputs[:, 0]\n",
    "y_pred_neutral = outputs[:, 1]\n",
    "\n",
    "ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)\n",
    "ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)\n",
    "ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)\n",
    "\n",
    "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_only:.4f}\")\n",
    "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_only:.4f}\")\n",
    "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_only:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like the transformer outperforms the model built on TF-IDF reprensentation.\n",
    "Unfortunately, running a transformer that big in FHE would be highly inefficient. \n",
    "\n",
    "Let's see if we can leverage transformer representation and train an FHE model for the given classification task. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 13176/13176 [03:21<00:00, 65.50it/s]\n",
      "100%|██████████| 1464/1464 [00:22<00:00, 66.31it/s]\n"
     ]
    }
   ],
   "source": [
    "# Function that transforms a list of texts to their representation\n",
    "# learned by the transformer.\n",
    "\n",
    "\n",
    "def text_to_tensor(\n",
    "    list_text_X_train: list,\n",
    "    transformer_model: AutoModelForSequenceClassification,\n",
    "    tokenizer: AutoTokenizer,\n",
    "    device: str,\n",
    ") -> numpy.ndarray:\n",
    "    # Tokenize each text in the list one by one\n",
    "    tokenized_text_X_train_split = []\n",
    "    for text_x_train in list_text_X_train:\n",
    "        tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors=\"pt\"))\n",
    "\n",
    "    # Send the model to the device\n",
    "    transformer_model = transformer_model.to(device)\n",
    "    output_hidden_states_list = []\n",
    "\n",
    "    for tokenized_x in tqdm.tqdm(tokenized_text_X_train_split):\n",
    "        # Pass the tokens through the transformer model and get the hidden states\n",
    "        # Only keep the last hidden layer state for now\n",
    "        output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[\n",
    "            1\n",
    "        ][-1]\n",
    "        # Average over the tokens axis to get a representation at the text level.\n",
    "        output_hidden_states = output_hidden_states.mean(dim=1)\n",
    "        output_hidden_states = output_hidden_states.detach().cpu().numpy()\n",
    "        output_hidden_states_list.append(output_hidden_states)\n",
    "\n",
    "    return numpy.concatenate(output_hidden_states_list, axis=0)\n",
    "\n",
    "\n",
    "# Let's vectorize the text using the transformer\n",
    "list_text_X_train = text_X_train.tolist()\n",
    "list_text_X_test = text_X_test.tolist()\n",
    "\n",
    "X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)\n",
    "X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={&#x27;max_depth&#x27;: [1], &#x27;n_bits&#x27;: [2, 3],\n",
       "                         &#x27;n_estimators&#x27;: [10, 30, 50], &#x27;n_jobs&#x27;: [-1]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={&#x27;max_depth&#x27;: [1], &#x27;n_bits&#x27;: [2, 3],\n",
       "                         &#x27;n_estimators&#x27;: [10, 30, 50], &#x27;n_jobs&#x27;: [-1]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</pre></div></div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
       "                         'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
       "             scoring='accuracy')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Now we have a representation for each tweet, we can train a model on these.\n",
    "grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
    "grid_search.fit(X_train_transformer, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best score: 0.8380388585306618\n",
      "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
     ]
    }
   ],
   "source": [
    "# Check the accuracy of the best model\n",
    "print(f\"Best score: {grid_search.best_score_}\")\n",
    "\n",
    "# Check best hyper-parameters\n",
    "print(f\"Best parameters: {grid_search.best_params_}\")\n",
    "\n",
    "# Extract best model\n",
    "best_model = grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8504\n",
      "Average precision score for positive class: 0.8917\n",
      "Average precision score for negative class: 0.9597\n",
      "Average precision score for neutral class: 0.7341\n"
     ]
    }
   ],
   "source": [
    "# Compute the metrics for each class\n",
    "\n",
    "y_proba = best_model.predict_proba(X_test_transformer)\n",
    "\n",
    "# Compute the accuracy\n",
    "y_pred = numpy.argmax(y_proba, axis=1)\n",
    "accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)\n",
    "print(f\"Accuracy: {accuracy_transformer_xgboost:.4f}\")\n",
    "\n",
    "y_pred_positive = y_proba[:, 2]\n",
    "y_pred_negative = y_proba[:, 0]\n",
    "y_pred_neutral = y_proba[:, 1]\n",
    "\n",
    "ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)\n",
    "ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)\n",
    "ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)\n",
    "\n",
    "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_xgboost:.4f}\")\n",
    "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_xgboost:.4f}\")\n",
    "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_xgboost:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our FHE-friendly XGBoost model does 38% better than the XGBoost model built over TF-IDF representation of the text. Note that here we are still not using FHE and only evaluating the model.\n",
    "Interestingly, using XGBoost over the transformer representation of the text matches the performance of the transformer model alone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 most positive tweets (class 2):\n",
      "@SouthwestAir love them! Always get the best deals!\n",
      "@AmericanAir THANK YOU FOR ALL THE HELP!  :P You guys are the best.  #americanairlines #americanair\n",
      "@SouthwestAir - Great flight from Phoenix to Dallas tonight!Great service and ON TIME! Makes @timieyancey very happy! http://t.co/TkVCMhbPim\n",
      "@AmericanAir AA2416 on time and awesome flight. Great job American!\n",
      "@SouthwestAir AMAZING c/s today by SW thank you SO very much. This is the reason we fly you #southwest\n",
      "----------------------------------------------------------------------------------------------------\n",
      "5 most negative tweets (class 0):\n",
      "@AmericanAir This entire process took sooooo long that no decent seats are left.  #customerservice\n",
      "@USAirways Not only did u lose the flight plan! Now ur flight crew is FAA timed out! Thx for havin us sit on the tarmac for an hr! #Pathetic\n",
      "@United site errored out at last step of changing award. Now can't even pull up reservation. 60 minute wait time.  Thanks @United!\n",
      "@united OKC ticket agent Roger McLarren(sp?) LESS than helpful with our Intl group travel problems Can't find a supervisor for help.\n",
      "@AmericanAir the dinner and called me \"hon\". Not the service I would expect from 1st class.  #disappointed\n"
     ]
    }
   ],
   "source": [
    "# Get probabilities predictions in clear\n",
    "y_pred_test = best_model.predict_proba(X_test_transformer)\n",
    "\n",
    "# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
    "print(\"5 most positive tweets (class 2):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])\n",
    "\n",
    "print(\"-\" * 100)\n",
    "\n",
    "print(\"5 most negative tweets (class 0):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n",
      "@USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news!\n",
      "@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n",
      "@USAirways your saving grace was our flight attendant Dallas who was amazing. wish he would transfer to Delta where I would see him again\n",
      "@AmericanAir that luggage you forgot...#mia.....he just won an oscar😄💝💝💝\n",
      "@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\n",
      "----------------------------------------------------------------------------------------------------\n",
      "5 most negative (predicted) tweets that are actually positive (ground truth class 2):\n",
      "@united thanks for updating me about the 1+ hour delay the exact second I got to ATL. 🙅🙅🙅\n",
      "@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\n",
      "@SouthwestAir save mile to visit family in 2015 and this will impact how many times I can see my mother.  I planned and you change the rules\n",
      "@SouthwestAir hot stewardess flipped me off\n",
      "@SouthwestAir - We left iPad in a seat pocket.  Filed lost item report. Received it exactly 1 week Late Flightr.  Is that a record?  #unbelievable\n"
     ]
    }
   ],
   "source": [
    "# Now let's see where the model is wrong\n",
    "y_pred_test_0 = y_pred_test[y_test == 0]\n",
    "text_X_test_0 = text_X_test[y_test == 0]\n",
    "\n",
    "print(\"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])\n",
    "\n",
    "print(\"-\" * 100)\n",
    "\n",
    "y_pred_test_2 = y_pred_test[y_test == 2]\n",
    "text_X_test_2 = text_X_test[y_test == 2]\n",
    "print(\"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\")\n",
    "for i in range(5):\n",
    "    print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Interestingly, these misclassifications are not obvious and some actually look rather like mislabeled. Also, it seems that the model is having a hard time to find ironic tweets.\n",
    "\n",
    "Now we have our model trained which has some great accuracy. Let's have it predict over the encrypted representation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sentiment Analysis of the Tweet with Fully Homomorphic Encryption\n",
    "\n",
    "Now that we have our model ready for FHE inference and our data ready for encryption let's use the model in a privacy preserving manner with FHE."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Compilation time: 8.5649 seconds\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 1/1 [00:00<00:00, 17.89it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FHE inference time: 0.8370 seconds\n"
     ]
    }
   ],
   "source": [
    "# Compile the model to get the FHE inference engine\n",
    "# (this may take a few minutes depending on the selected model)\n",
    "start = time.perf_counter()\n",
    "best_model.compile(X_train_transformer)\n",
    "end = time.perf_counter()\n",
    "print(f\"Compilation time: {end - start:.4f} seconds\")\n",
    "\n",
    "\n",
    "# Let's write a custom example and predict in FHE\n",
    "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
    "X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)\n",
    "clear_proba = best_model.predict_proba(X_tested_tweet)\n",
    "\n",
    "# Now let's predict with FHE over a single tweet and print the time it takes\n",
    "start = time.perf_counter()\n",
    "decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe=\"execute\")\n",
    "end = time.perf_counter()\n",
    "fhe_exec_time = end - start\n",
    "print(f\"FHE inference time: {fhe_exec_time:.4f} seconds\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Probabilities from the FHE inference: [[0.08434131 0.05571389 0.8599448 ]]\n",
      "Probabilities from the clear model: [[0.08434131 0.05571389 0.8599448 ]]\n"
     ]
    }
   ],
   "source": [
    "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
    "print(f\"Probabilities from the clear model: {clear_proba}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's export the final model such that we can reuse it in a client/server environment\n",
    "\n",
    "# Export some data to be used for compilation\n",
    "X_train_numpy = X_train_transformer[:100]\n",
    "\n",
    "# Merge the two arrays in a pandas dataframe\n",
    "X_test_numpy_df = pd.DataFrame(X_train_numpy)\n",
    "\n",
    "# to csv\n",
    "X_test_numpy_df.to_csv(\"samples_for_compilation.csv\")\n",
    "\n",
    "# Let's save the model to be pushed to a server later\n",
    "from concrete.ml.deployment import FHEModelDev\n",
    "\n",
    "fhe_api = FHEModelDev(\"sentiment_fhe_model\", best_model)\n",
    "fhe_api.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Accuracy</th>\n",
       "      <th>Average Precision (positive)</th>\n",
       "      <th>Average Precision (negative)</th>\n",
       "      <th>Average Precision (neutral)</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Model</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>TF-IDF + XGBoost</th>\n",
       "      <td>0.681011</td>\n",
       "      <td>0.561521</td>\n",
       "      <td>0.834914</td>\n",
       "      <td>0.382002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Transformer Only</th>\n",
       "      <td>0.805328</td>\n",
       "      <td>0.854827</td>\n",
       "      <td>0.954804</td>\n",
       "      <td>0.680110</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Transformer + XGBoost</th>\n",
       "      <td>0.850410</td>\n",
       "      <td>0.891691</td>\n",
       "      <td>0.959747</td>\n",
       "      <td>0.734144</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       Accuracy  Average Precision (positive)   \n",
       "Model                                                           \n",
       "TF-IDF + XGBoost       0.681011                      0.561521  \\\n",
       "Transformer Only       0.805328                      0.854827   \n",
       "Transformer + XGBoost  0.850410                      0.891691   \n",
       "\n",
       "                       Average Precision (negative)   \n",
       "Model                                                 \n",
       "TF-IDF + XGBoost                           0.834914  \\\n",
       "Transformer Only                           0.954804   \n",
       "Transformer + XGBoost                      0.959747   \n",
       "\n",
       "                       Average Precision (neutral)  \n",
       "Model                                               \n",
       "TF-IDF + XGBoost                          0.382002  \n",
       "Transformer Only                          0.680110  \n",
       "Transformer + XGBoost                     0.734144  "
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "# Let's print the results obtained in this notebook\n",
    "df_results = pd.DataFrame(\n",
    "    {\n",
    "        \"Model\": [\"TF-IDF + XGBoost\", \"Transformer Only\", \"Transformer + XGBoost\"],\n",
    "        \"Accuracy\": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],\n",
    "        \"Average Precision (positive)\": [\n",
    "            ap_positive_tfidf,\n",
    "            ap_positive_transformer_only,\n",
    "            ap_positive_transformer_xgboost,\n",
    "        ],\n",
    "        \"Average Precision (negative)\": [\n",
    "            ap_negative_tfidf,\n",
    "            ap_negative_transformer_only,\n",
    "            ap_negative_transformer_xgboost,\n",
    "        ],\n",
    "        \"Average Precision (neutral)\": [\n",
    "            ap_neutral_tfidf,\n",
    "            ap_neutral_transformer_only,\n",
    "            ap_neutral_transformer_xgboost,\n",
    "        ],\n",
    "    }\n",
    ")\n",
    "df_results.set_index(\"Model\", inplace=True)\n",
    "df_results  # pylint: disable=pointless-statement"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Conclusion\n",
    "\n",
    "In this notebook we presented two different ways to represent a text.\n",
    "1. Using TF-IDF vectorization\n",
    "2. Using the hidden layers from a transformer\n",
    "\n",
    "Both representation are then used to train a machine learning model will run in FHE (here XGBoost)\n",
    "\n",
    "Once the model is trained, clients can send encrypted text representation to the server to get a sentiment analysis done and they receive the probability for each class (negative, neutral and positive) in an encrypted format which can then be decrypted by the client. For now, all the FHE magic (encrypt, predict and decrypt) is done within the `predict_proba` function with the argument `fhe='execute'`. In the next release, an API will be provided to split the server/client parts.\n",
    "\n",
    "Regarding the FHE execution times, the final XGboost model can predict over an encrypted data point in ~4 seconds. This will change depending on the number of threads available. In the future, more hardware acceleration will be available to speed up the execution time.\n",
    "\n",
    "It seems that the combination of a transformer (thanks Huggingface!) with a \"simpler\" model such as XGBoost works pretty well. Thanks to Concrete ML library, we can easily use this text representation on the client machine and then encrypt it to send it to a remote server without having to deal with a transformer runtime in FHE."
   ]
  }
 ],
 "metadata": {
  "execution": {
   "timeout": 10800
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
